import loginApi from '@/api/auth/loginApi'
import userCenterApi from '@/api/sys/userCenterApi'
import DictDataApi from '@/api/set/DictDataApi'
import router from '@/router'
import tool from '@/utils/tool'
import { message } from 'ant-design-vue'
import { useGlobalStore } from '@/store'
import routerUtil from '@/utils/routerUtil'
import sysConfig from '@/config/index'
// import { config } from '@/utils/template'
export const afterLogin = async (loginUser) => {
	tool.data.set(sysConfig.ACCESS_TOKEN, loginUser.accessToken)
	tool.data.set(sysConfig.CLIENT_ID, loginUser.clientId)
	tool.data.set(sysConfig.REFRESH_TOKEN, loginUser.refreshToken)
	tool.data.set(sysConfig.USER_ID, loginUser.userId)
	tool.data.set(sysConfig.USER_TYPE, loginUser.userType)
	tool.data.set(sysConfig.TENANT_ID, loginUser.tenantId)
	// 获取登录的用户信息
	const loginUserInfo = await loginApi.getLoginUser()
	if (!loginUserInfo) {
		tool.data.set(sysConfig.ACCESS_TOKEN, null)
	}
	const globalStore = useGlobalStore()
	globalStore.setUserInfo(loginUserInfo.user)
	tool.data.set(sysConfig.USER_INFO, loginUserInfo.user)
	// 获取用户的菜单
	const menu = loginUserInfo.menus //  await userCenterApi.userLoginMenu()
	let indexMenu = routerUtil.getIndexMenu(menu).path
	tool.data.set(sysConfig.MENUS, menu)
	// tool.data.set(sysConfig.PERMISSIONS, loginUserInfo.permissions)
	// 重置系统默认应用
	tool.data.set('SNOWY_MENU_MODULE_ID', menu[0].id)
	message.success('登录成功')
	if (tool.data.get('LAST_VIEWS_PATH')) {
		// 如果有缓存，将其登录跳转到最后访问的路由
		indexMenu = tool.data.get('LAST_VIEWS_PATH')
	}
	// 如果存在退出后换新账号登录，进行重新匹配，匹配无果则默认首页
	if (menu) {
		let routerTag = 0
		menu.forEach((item) => {
			if (item.children) {
				if (JSON.stringify(item.children).indexOf(indexMenu) > -1) {
					routerTag++
				}
			}
		})
		if (routerTag === 0) {
			// 取首页
			indexMenu = routerUtil.getIndexMenu(menu).path
		}
	}
	DictDataApi.list().then((data) => {
		// 设置字典到store中
		tool.data.set('DICT_DATA', data)
	})
	await router.replace({
		path: indexMenu
	})
}
